// pages/order/order.js
import { Order } from "order-model";
import { Cart } from "../cart/cart-model";
import {Address} from '../../utils/address';
var address = new Address();
var cart  = new Cart();
var order = new Order();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form:'cart'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var account = options.account;
    var from = options.from;
    if(from == 'cart'){
      this._fromCart(account,from);
    }else if(from == 'my'){
      this.data.id = account;
      this.setData({
        from:from
      })
    }else{
     this.data.id = options.id;
    }
  },

  //购物车加载
  _fromCart:function (account,from) { 
    var productsArr = cart.getCartDataFromLocal(true);
    this.setData({
        from: from,
        productsArr: productsArr,
        account: account,
        orderStatus: 0
    });
    address.getAddress((res) => {
      this._bindAddressInfo(res);
  });
 },

   /*绑定地址信息*/
   _bindAddressInfo: function (addressInfo) {
    this.setData({
        addressInfo: addressInfo
    });
},
// 添加地址
editAddress: function (event) {
  var that = this;
  wx.chooseAddress({
      success: (res) => {
        var addressInfo = {
          name: res.userName,
          mobile: res.telNumber,
          totalDetail: address.setAddressInfo(res),
      }
      this.updateAddress(res,addressInfo)
    },
  });
},
    updateAddress(res,addressInfo){
      address.submitAddress(res,(data)=>{
        this._bindAddressInfo(addressInfo);
      },(err)=>{
      if(err.code ==401){
        wx.navigateTo({
          url: '../login/login',
        });
      }else{
          this.showTips('操作提示', '地址信息更新失败！');
      }
      })
    },

   /*绑定地址信息*/
   _bindAddressInfo: function (addressInfo) {
    this.setData({
        addressInfo: addressInfo
    });
  },
  pay(){
    if (!this.data.addressInfo) {
      this.showTips('下单提示', '请输入您的收货地址');
    }
   if(this.data.orderStatus == 0){
    this._firstTimePay();
   }else{
     this.cartPayOrder(this.data.id);
   }
  },

   //创建订单
   _firstTimePay: function () {
    var orderInfo = [];
    var procuctInfo = this.data.productsArr;
    for (let i = 0; i < procuctInfo.length; i++) {
        orderInfo.push({
            value_id: procuctInfo[i].id,
            counts: procuctInfo[i].counts
        });
    }
   this.addorder(orderInfo);
  },

  addorder(data){
    order.addOrder(data, res =>{
       if(res.pass == true){
          this.cartPayOrder(res.order_id);
       }else{
        this.OffOrder(res.pStatusArray);
       }
    },err =>{
      if(err.errorCode == 40001){
        var str = err.msg;
        var code = str.lastIndexOf("的");
        var id = str.substring(0,code);
        this.offGoods(id);
      }else{
        if(err.code == 401){
          wx.navigateTo({
            url: '../login/login',
          });
        }else{
          wx.showModal({
            title: "提示",
            content: err.msg,
            showCancel: false,
           })
        }
      }
    })
  },

  offGoods(id){
    var str = '';
    var ov = ''
    var array = this.data.productsArr;
    for (const key in array) {
         if(id = array[key].id){
           str += '商品：'+array[key].goods_name+'\r\n';
           ov += '规格:'+array[key].value_name+'已下架'+'\r\n';
         }
    }
    wx.showModal({
     title: "商品已下架提示",
     content: str+ov,
     showCancel: false,
    })
  },

  OffOrder(data){
    var id = 0;
     for (const key in data) {
         if(data[key].haveStock == false){
              id = data[key].id;
         }
     }
   var str = '';
   var ov = ''
   var array = this.data.productsArr;
   for (const key in array) {
        if(id = array[key].id){
          str += '商品：'+array[key].goods_name+'\r\n';
          ov += '规格:'+array[key].value_name+'库存不足'+'\r\n';
        }
   }
   wx.showModal({
    title: "库存不足提示",
    content: str+ov,
    showCancel: false,
   })
  },

  cartPayOrder(id){
    order.payOrder(id,res =>{
      if(res.pass == true){
        this.onOrOffPay(res.order_no,res.order_id);
      }else{
       this.OffOrder(res.pStatusArray);
      }
   },err =>{
     if(err.errorCode == 40001){
       var str = err.msg;
       var code = str.lastIndexOf("的");
       var id = str.substring(0,code);
       this.offGoods(id);
     }else{
      if(err.code == 401){
        wx.navigateTo({
          url: '../login/login',
        });
      }else{
        wx.showModal({
          title: "提示",
          content: err.msg,
          showCancel: false,
         })
      }
     }
   })
  },

  onOrOffPay(order_no,id){
    this.deleteProducts();
    order.execSetStorageSync(true);
    var that = this;
    wx.showModal({
        title: '选择结果',
        content: '支付成功或失败',
        showCancel: true,
        cancelText: '失败',
        cancelColor: '#000000',
        confirmText: '成功',
        confirmColor: '#3CC51F',
        success: (result) => {
          if(result.confirm){
            order.payCallBack(order_no,res =>{
                  that.payRequst(true,id)
            })
          }else{
            that.payRequst(false,id);
          }
        },
      });
  },

    //支付结果
    payRequst: function (payResult,id) {
      this.data.id = id;
      this.deleteProducts();
      wx.navigateTo({
          url: '../pay-result/pay?payResult=' + payResult + '&id=' + id + '&from=order',
          success: (result) => {

          },
      });
  },

  /** 
    * 提示窗口
    * params:
    * title - {string}标题
    * content - {string}内容
    * flag - {bool}是否跳转到 "我的页面"
    */
   showTips: function (title, content, flag) {
    wx.showModal({
        title: title,
        content: content,
        showCancel: false,
        success: function (res) {
            if (flag) {
                wx.switchTab({
                    url: '/pages/my/my'
                });
            }
        }
    });
},
 //将已经下单的商品从购物车删除
    deleteProducts: function () {
      var ids = [], arr = this.data.productsArr;
      for (let i = 0; i < arr.length; i++) {
          ids.push(arr[i].id);
      }
      cart.delete(ids);
    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.id) {
       var id = this.data.id;
       var that = this;
       order.getOrder(id,res=>{
         this.setData({
           id:res.id,
           orderStatus: res.status,
           productsArr: res.value,
           account: res.total_price,
           basicInfo: {
            orderTime: res.create_time,
            orderNo: res.order_no,
            pay_time:res.pay_time,
            overdue_pay_time:res.overdue_pay_time
        },
      });
      var addressInfo = res.snap_address;
      addressInfo.totalDetail = address.setAddressInfo(addressInfo);
      this._bindAddressInfo(addressInfo);
       },err =>{

       })
   }
  },

  unpackValue(data){
    var list = [];
    for (const key in data) {
        var array = this.setValue(data[key].goods_icon,data[key].goods_name,data[key].value)
        list = list.concat(array);
    }
   return list;
  },

  setValue(goods_icon,goods_name,value){
      var data = [];
      for (const key in value) {
           value[key].goods_icon = goods_icon;
           value[key].goods_name = goods_name;
           value[key].value_name = value[key].name;
           data.push(value[key])
      }
      return data;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})